var app = angular.module('meetingApp.services',[]);

app.service('toastPCService', [function () {
    var service = {};
    /*
     type: 1 成功   2警告  3 错误
     */
    service.show = function (type, text, time) {
        var shortCutFunction = "warning";
        if (angular.isString(type)) {
            time = text;
            text = type;
            type = 1;
        }
        time = time || 2500;
        switch (type) {
            case 1: shortCutFunction = "success"; break;
            case 2: shortCutFunction = "warning"; break;
            case 3: shortCutFunction = "error"; break;
        }
        if (window.toastr) {
            window.toastr.options = {
                "closeButton": true,
                "debug": false,
                "progressBar": false,
                "positionClass": "toast-top-right",
                "onclick": null,
                "showDuration": "400",
                "hideDuration": "888",
                "timeOut": time,
                "extendedTimeOut": 888,
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            };
            window.toastr[shortCutFunction](text)
        }
    };
    return service;
}]);

app.service('session' , [function(){
	return {
		set : function(key , val){
			if(val === null){
				sessionStorage.removeItem(key);
				return;
			}
			var data = angular.copy(val);
			var unhashKey = function(data){
				if(typeof data == 'object'){
					for(k in data){
						if(data[k] && data[k]['$$hashKey']){
							delete data[k]['$$hashKey'];
						}
					}
				}
			}
			unhashKey(data);
			sessionStorage[key] = JSON.stringify(data);
		},
		get : function(key){
			var val = sessionStorage[key];
			if(val && val != 'undefined' && val != 'null'){
				return JSON.parse(val);
			}
			return null;
		}
	}
}])

//保存临时数据共控制器之间使用
app.service('tempDataService', [function () {
    var tempData = [];
    return {
        set: function (key, val) {
            tempData[key] = val;
        },
        get: function (key) {
            return tempData[key] || null;
        }
    };
}]);


app.service('layerService' , [function(){
	var service = {
			alert :function(msg){
				layer.alert(msg);
			},
			msg : function(msg){
				layer.msg(msg)
			},
			confirm : function(msg , btn , commit,cancel){
				layer.confirm(msg , {btn : btn || ['确定','取消']},function(index){
					commit && commit();
					layer.close(index);
				},function(index){
					cancel && cancel();
					layer.close(index);
				})
			},
			load : function(){
				return layer.load(1 , {shade : [0.1 ,'#eff']})
			}
	};
	return service;
}])


app.service('ajaxService' , ['$http' , 'toastPCService','layerService',function($http , toastPCService,layerService){
	var sendAjax = function(url , method , params ,cb ,cb2 , loding){
		method = method.toLocaleUpperCase();
		var body = angular.copy(params);
		var unNullVal = function(arr){
			for(i in arr){
				if(arr[i] === null){
					arr[i] = '';
				}
				if(typeof(arr[i]) === 'object'){
					unNullVal(arr[i]);
				}
			}
		};
		unNullVal(body);
		for (var k in body) {
            if (body.hasOwnProperty(k)) {
            	if (k.indexOf("$") != -1) {
                    url.replace("{" + k + "}", body[k]);
                    delete  body[k];
                }
                if (typeof(body[k]) === 'object') {
                    body[k] = JSON.stringify(body[k]);
                }
            }
        }
		var header = {
				'Accept': '*/*',
	            'X-Requested-With': 'XMLHttpRequest',
	            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
		};
		
		var layerIndex = 0;
		if(loding){
			layerIndex = layerService.load();
		}
		
		var verifyErrCode = function(rel){
			if(rel.errCode){
				switch(rel.errCode){
					case 100001: window.location.path = "/admin/login";break;
					case 100002: toastPCService.show(3 , rel.message);
					default :
						if(rel.message){
							toastPCService.show(2 , rel.message)
						}
				}
			}
		}
		if(window._host){
			url = window._host + url;
		}
		switch(method){
			case "GET":
				var config = {params : body , headers : header};
				$http.get(url , config).success(function(rel){
					layer.close(layerIndex);
					verifyErrCode(rel);
					cb && cb(rel);
				}).error(function(err){
					layer.close(layerIndex);
					toastPCService.show(3 , '访问服务器失败');
					cb2 && cb2(err);
				})
				break;
			case "POST":
				var params = '';
                for (i in body) {
                    params += i + "=" + encodeURIComponent(body[i]) + "&";
                }
                params = params.substr(0, params.length - 1);
				$http.post(url , params , {headers : header}).success(function(rel){
					layer.close(layerIndex);
					verifyErrCode(rel);
					cb && cb(rel);
				}).error(function(err){
					layer.close(layerIndex);
					toastPCService.show(3 , '访问服务器失败');
					cb2 && cb2(err);
				})
				break;
		}
	}
	var service = function(method , opts , cb , cb2 , hideLoding){
		if(typeof cb2 == 'boolean'){
			hideLoding = cb2;
		}
		var loding = hideLoding ? false : true;
		if (typeof(method) === "object") {
            mm = method
        } else {
            mm = window._AppConfig.AjaxApi[method];
        }

        if (mm) {
        	sendAjax(mm.url, mm.method, opts, cb, cb2 , loding);
        } else {
            //未找到方法
            console.log("url 错误", "返回结果：err = ", "无法请求，无效的请求！", "\n");
            toastPCService.show(3, "无效的请求");
            cb2 && cb2({errCode: -1, message: "无效的请求"})
        }
	}
	return service;
}])

